package com.gxa.interceptor;

import com.gxa.exception.NoAjaxException;
import com.gxa.exception.SystemException;
import com.gxa.pojo.Auth;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 权限拦截器
 */
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
        * 权限拦截的思路：
        *  通过request 去获取 servletPath
        *  通过session 获取是否是超级管理员
        *      是： 直接放行
        *      不是： servletPath 和权限列表进行匹配， 有就放行， 没有就拦截
        * */
        HttpSession session = request.getSession();
        Boolean isSuper = (Boolean) session.getAttribute("isSuper");
        if (isSuper){
            // 超级管理员直接放行
            return true;
        }
        // 非超级管理员
        // 获取请求路径
        String servletPath = request.getServletPath();
        // 获取权限
        List<Auth> authList = (List<Auth>) session.getAttribute("authList");
        for (Auth auth : authList) {
            if (auth.getAuthUrl() == null) {
                continue;
            }
            if (auth.getAuthUrl().equals(servletPath)) {
                return true;
            }
        }
        // 判断是否是ajax请求
        if (isAjax(request)){
            throw new SystemException(1005, "对不起，你不配！");
        }
        throw new NoAjaxException(1005, "对不起，你不配！");

    }


    /**
     * 判断是否是ajax请求
     * @param request
     * @return
     */
    private Boolean isAjax(HttpServletRequest request){
        String header = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(header)){
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
